// 异步请求数据，并且对比原有数据
// 对差异数据播报
function query(i) {
  var queryUrl = 'ezfm/problem/details/conditon/query';
  var project_id = window.top.frames[i].document.getElementsByName('project_id')[0].value;
  var state = window.top.frames[i].document.getElementsByName('state')[0].value;
  var device_tag = window.top.frames[i].document.getElementsByName('device_tag')[0].value;
  var device_name = window.top.frames[i].document.getElementsByName('device_name')[0].value;
  var class_id = window.top.frames[i].document.getElementsByName('class_id')[0].value;
  var type_id = window.top.frames[i].document.getElementsByName('type_id')[0].value;
  var create_time1 = window.top.frames[i].document.getElementsByName('create_time1')[0].value;
  var create_time2 = window.top.frames[i].document.getElementsByName('create_time2')[0].value;
  var postData = JSON.stringify({
    class_id: class_id,
    create_time1: create_time1,
    create_time2: create_time2,
    device_name: device_name,
    device_tag: device_tag,
    limit: 100,
    project_id: project_id,
    start: 0,
    state: state,
    type_id: type_id
  });
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      var newdata = xmlHttp.response['data'];
      var newReq = newdata.filter(nd => (new Date(nd['create_time'])) > last_update_time);
      var remindlist = []
      if (newReq.length > 0) {
        var c_time = new Date(newReq[0]['create_time']);
        last_update_time = c_time.getTime();
        if (showMessageFlag) {
          newReq.forEach((d, index) => {
            info(i, d['details_number'] + ' ' + d['typename'] + ' ' + d['detailed_address'] + ' ' + d['details_content'] + ' 联系电话：' + d['customer_number'])
          });
        }

        // http://stackmirror.caup.cn/page/rhodtn49pq29
        // var newReq = ['你好', '世界', '中文'];
        var welcomestr = $("li.first a").text()
        var contuct = ' 联系电话：';
        var prompt = '有新订单请及时处理，';
        if (welcomestr.indexOf("Welcome")!=-1){
               prompt = 'Please handle new order ';
               contuct = 'contuct number: '

        }

        var d = newReq[0];
        var message = prompt + d['detailed_address'] + ' ' + d['details_content'] + contuct + d['customer_number'];
        var index = 1;
        var tts_url = 'http://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=morimatsu&tok=24.e1316badf71c14d2f59a5e01e5f317e1.2592000.1575459546.282335-10550628&vol=9&per=0&spd=5&pit=5&aue=3&tex=' + encodeURI(encodeURIComponent(message));
        var remind = new Audio(tts_url);
        remind.play();
        remind.onended = function () {
          if (index < newReq.length) {
            d = newReq[index];
            message = prompt + d['detailed_address'] + ' ' + d['details_content'] + contuct + d['customer_number'];
            remind.src = 'http://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=morimatsu&tok=24.e1316badf71c14d2f59a5e01e5f317e1.2592000.1575459546.282335-10550628&vol=9&per=0&spd=5&pit=5&aue=3&tex=' + encodeURI(encodeURIComponent(message));
            remind.play();
            index++;
          }
        }
      }

    }
  }
  xmlHttp.open('post', queryUrl);
  xmlHttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
  xmlHttp.responseType = 'json';
  xmlHttp.send(postData);
}


// 注入通知内容
function info(i, txt) {
  var e = document.createElement('div');
  e.innerHTML = 'New Requirement:' + txt;
  e.setAttribute('class', 'info');
  e.addEventListener("click", function () {
    this.remove();
  });
  e.setAttribute('style', 'background:#1a59b7;color:#ffffff;overflow:hidden;z-index:9999;padding:5px;text-align:left;width:1000px;height:22px;')
  window.top.frames[i].document.body.prepend(e);

}

// 清除通知
function removeInfo(i) {
  Array.from(window.top.frames[i].document.getElementsByClassName('info')).forEach((e, i) => {
    e.remove();
  });
}

// 主程序 Bookmarklet 调用此程序
function addtask() {
  if (window.top.document.getElementsByClassName('mmToolBar').length == 0) {
    loadCss();
  } else {
    console.log('Toolbar Already Loaded');
  }
}


// 注入 Bootstrap 完成之后绘制 用户UI
function loadCss() {
  (function () {
    var css = document.createElement("link");
    css.href = 'https://cdn.bootcss.com/twitter-bootstrap/4.1.3/css/bootstrap.css';
    //css.href = 'https://cdn.bootcss.com/pure/1.0.0/base.css';
    css.type = 'text/css';
    css.rel = 'stylesheet';
    css.onload = function () {
      console.log('Load Css Successfully!');
      addToolBar();
    };
    window.top.document.head.appendChild(css);
  })();
}

// 注入 工具栏
function addToolBar() {
  var toolbar = document.createElement('div');
  toolbar.setAttribute('class', 'mmToolBar jumbotron jumbotron-fluid');
  // toolbar.addEventListener("click", function () {this.remove();});
  toolbar.setAttribute('style', 'position: absolute; top: 10px; left: 300px; width: 500px; height: 58px; padding: 5px; z-index: 100;');
  toolbar.innerHTML = [
    '<div class="form-row align-items-center">',
    '<div class="col-auto my-1 mmClose" style="display:none">',
    '<button id="mmCloseId" class="btn btn-success">关闭定时播报</button>',
    '</div>',
    '<div class="col-auto my-1 mmCreate">',
    '<button id="mmCreateId" class="btn btn-primary">打开定时播报</button>',
    '</div>',
    '<div class="col-sm-3 my-1 mmCreate">',
    '<input type="text" class="form-control" id="intervalId" value="3000">',
    '</div>',
    '<div class="col-sm-3 my-1 mmCreate">',
    '<input type="text" class="form-control" id="frameId" value="1">',
    '</div>',
    '<div class="col-auto my-1 mmCreate">',
    '<div class="form-check">',
    '<input class="form-check-input" type="checkbox" id="mmShowMessageId">',
    '<label class="form-check-label" for="autoSizingCheck2">',
    '显示提醒',
    '</label>',
    '</div>',
    '</div>',
    '</div>'
  ].join('\n');

  // jQuery(document).ready(function(){bindClickEvent();}) is a good way
  // i can't achieve it using pure javascript
  // setTimeout is an effective way even though it's not elegent
  setTimeout(function () {
    bindClickEvent();
  }, 200);

  window.top.document.body.appendChild(toolbar);
}

// 清除工具栏 一般不用
function removeToolBar() {
  Array.from(window.top.document.getElementsByClassName('mmToolBar')).forEach((e, i) => {
    e.remove();
  });
}

// 绑定按键
function bindClickEvent() {
  window.top.document.getElementById('mmCloseId').addEventListener('click', function () {
    Array.from(window.top.document.getElementsByClassName('mmClose')).forEach((e, i) => {
      e.style.display = 'none';
    });
    Array.from(window.top.document.getElementsByClassName('mmCreate')).forEach((e, i) => {
      e.style.display = 'block';
    });
    window.top.document.getElementsByClassName('mmToolBar')[0].style.width = '500px';
    window.top.document.getElementsByClassName('mmToolBar')[0].style.backgroundColor = '';
    clearInterval(parseInt(setIntervalId));
  });

  window.top.document.getElementById('mmCreateId').addEventListener('click', function () {
    window.top.document.getElementsByClassName('mmToolBar')[0].style.width = '140px';
    Array.from(window.top.document.getElementsByClassName('mmCreate')).forEach((e, i) => {
      e.style.display = 'none';
    });
    Array.from(window.top.document.getElementsByClassName('mmClose')).forEach((e, i) => {
      e.style.display = 'block';
    });
    window.top.document.getElementsByClassName('mmToolBar')[0].style.backgroundColor = 'transparent';
    console.log(window.top.document.getElementById('intervalId').value);
    console.log(window.top.document.getElementById('frameId').value);
    console.log(window.top.document.getElementById('mmShowMessageId').checked);

    var userinput = window.top.document.getElementById('intervalId').value;
    var interval = parseInt(userinput) || 0;
    // 如果合法则执行定时任务
    // 否则什么都不做
    if (interval > 0) {
      // 如果有定时任务，清除它
      if (typeof setIntervalId != 'undefined') {
        console.log("Find and clear IntervalId ", setIntervalId);
        clearInterval(parseInt(setIntervalId));
      }
      // 设置全局变量 setIntervalId
      // 用于下次执行时清除。
      frame = parseInt(window.top.document.getElementById('frameId').value) || 1;
      showMessageFlag = window.top.document.getElementById('mmShowMessageId').checked;
      var currentdate = new Date();
      last_update_time = currentdate.getTime()
      audio = new Audio('https://gitee.com/vanvenj/ezfm/raw/master/order.mp3');
      setIntervalId = setInterval(function () {
        window.parent.frames[frame].document.getElementById('btn_problem').click();
        query(frame);
      }, interval);
    }



  });
  window.top.document.getElementById('mmShowMessageId').addEventListener('click', function () {
    if (window.top.document.getElementById('mmShowMessageId').checked) {
      window.top.document.getElementById('mmShowMessageId').checked = true;
    } else {
      window.top.document.getElementById('mmShowMessageId').checked = false;
    }
  });
}